<?php
namespace app\index\controller;

use app\index\service\DataReturnService;
use app\index\common\Base;
use app\index\service\ProductService;
use think\Controller;
use app\index\common;
use think\Db;
use think\Exception;
use think\Loader;
use think\Request;
use app\index\controller\Log\InsertLog as IL;
use app\index\controller\Log\OperationLog as OL;

/**
 * 产品逻辑类
 */
class Product extends Controller
{
    /**
     * 2018-05-04
     * 曹振威
     * 规格列表
     */
    public function standard_list($systematics_id = 0){
        $where = [
            'system_id' => $this->system_id,
            'state' => 0,
            'systematics_id' => $systematics_id,
        ];
        $field = 'id,title';
        $row = Db::table('standard')->where($where)->field($field)->select();
        $date = array('code'=>666,'msg'=>'规格列表获取成功','data'=>$row);
       /* IL::insert('log', [
            'user_id'=>$this->user_id,
            'operation_user'=> $this->user['name'],
            'operation_name'=>'查看',
            'operation_content'=>'查看规格列表',  
            'operation_type'=>1,
            'ip'=> Request()->ip(),
            'state'=>1,
            'createtime'=>date('Y-m-d H:i:s'),
         ]);*/
        return $date;
    }  
            
     /**
     * 2018-4-18 日期格式
      * 2018-05-30  修改
     * 曹振威 开发人
     * 删除类目
     */
    public function systematics_delete($id = 0) {
        if(!$id){
            $date = array('code'=>20021,'msg'=>'非法操作','data'=>'');
            exit(json_encode($date));
        }
        $where = [
            'id' => $id,
            'system_id' => $this->system_id,
            ];
        $row = Db::table('systematics')->where($where)->setField('state',1);
        if($row){
            $date = array('code'=>666,'msg'=>'删除类目成功','data'=>'');
            IL::insert('log', [
                'user_id'=>$this->user_id,
                'operation_user'=> $this->user['name'],
                'operation_name'=>'删除',
                'operation_content'=>'删除类目/品牌/系列成功',  
                'operation_type'=>3,
                'ip'=> Request()->ip(),
                'state'=>1,
                'createtime'=>date('Y-m-d H:i:s'),
             ]);
        }else{
            $date = array('code'=>20037,'msg'=>'删除类目失败','data'=>'');
            IL::insert('log', [
                'user_id'=>$this->user_id,
                'operation_user'=> $this->user['name'],
                'operation_name'=>'删除',
                'operation_content'=>'删除类目/品牌/系列失败',  
                'operation_type'=>3,
                'ip'=> Request()->ip(),
                'state'=>0,
                'createtime'=>date('Y-m-d H:i:s'),
             ]);
        }
        return $date;
    }
    
    /**
     * 2018-05-30
     * czw
     * 获取父级类目的基因
     */
    public function get_superior_gene($systematics_id){
        if($systematics_id){
            $row = Db::table('systematics')->where('id',$systematics_id)->value('superior_gene');
            if($row == 0){
                return $systematics_id;
            }else{
                return $row.'-'.$systematics_id;
            }
        }else{
            return 0;
        }
    }
    
    /**
     * 2018-4-17 日期格式
     * 2018-05-30  修改
     * 曹振威 开发人
     * 添加/修改类目
     */
    public function systematics_add_edit($superior_id = 0,$title = '',$id = 0){
        //$systematics_id = 0 添加父级类目   有值   添加下级类目   基因  为父级基因加上父级
        if(!$title){
            $date = array('code'=>20099,'msg'=>'类目名称（title）不能为空','data'=>'');
            exit(json_encode($date));
        }
        $superior_gene = $this->get_superior_gene($superior_id);
        $systematics_insert = [
            'system_id' => $this->system_id,
            'superior_id' => $superior_id,
            'superior_gene' => $superior_gene,
            'title' => $title,
            'createtime' => date('Y-m-d H:i:s')
        ];
        $where['system_id'] = $this->system_id;
        if($systematics_insert){
            if($id){
                // 编辑
                $where['id'] = $id;
                $row_type = 1;
                $row = Db::table('systematics')->where($where)->update($systematics_insert);
            }else{
                // 添加
                $row_type = 2;
                $row = Db::table('systematics')->insert($systematics_insert);
            }
            
            if($row){
                if($row_type == 1){
                    $date = array('code'=>666,'msg'=>'编辑类目成功','data'=>'');
                    IL::insert('log', [
                        'user_id'=>$this->user_id,
                        'operation_user'=> $this->user['name'],
                        'operation_name'=>'编辑',
                        'operation_content'=>'编辑类目/品牌/系列成功',  
                        'operation_type'=>2,
                        'ip'=> Request()->ip(),
                        'state'=>1,
                        'createtime'=>date('Y-m-d H:i:s'),
                     ]);
                }elseif($row_type == 2){
                    $date = array('code'=>666,'msg'=>'添加类目成功','data'=>'');
                    IL::insert('log', [
                        'user_id'=>$this->user_id,
                        'operation_user'=> $this->user['name'],
                        'operation_name'=>'添加',
                        'operation_content'=>'添加类目/品牌/系列成功',  
                        'operation_type'=>2,
                        'ip'=> Request()->ip(),
                        'state'=>1,
                        'createtime'=>date('Y-m-d H:i:s'),
                     ]);
                }
                
            }else{
                if($row_type == 1){
                    $date = array('code'=>20036,'msg'=>'编辑类目失败','data'=>'');
                    IL::insert('log', [
                        'user_id'=>$this->user_id,
                        'operation_user'=> $this->user['name'],
                        'operation_name'=>'编辑',
                        'operation_content'=>'编辑类目/品牌/系列失败',  
                        'operation_type'=>2,
                        'ip'=> Request()->ip(),
                        'state'=>0,
                        'createtime'=>date('Y-m-d H:i:s'),
                     ]);
                }elseif($row_type == 2){
                    $date = array('code'=>20036,'msg'=>'添加类目失败','data'=>'');
                    IL::insert('log', [
                        'user_id'=>$this->user_id,
                        'operation_user'=> $this->user['name'],
                        'operation_name'=>'添加',
                        'operation_content'=>'添加类目/品牌/系列失败',  
                        'operation_type'=>2,
                        'ip'=> Request()->ip(),
                        'state'=>0,
                        'createtime'=>date('Y-m-d H:i:s'),
                     ]);
                }
            }
        }
        return $date;
    }
    
    /**
     * 2018-4-18 日期格式
     * 曹振威 开发人
     * 单个删除规格
     */
    public function standard_del($id = 0) {
        if(!$id){
            $date = array('code'=>20021,'msg'=>'非法操作','data'=>'');
            exit(json_encode($date));
        }
        $where = [
            'id' => $id,
            'system_id' => $this->system_id,
            ];
        $row = Db::table('standard')->where($where)->setField('state',1);
        if($row){
            $date = array('code'=>666,'msg'=>'删除规格成功','data'=>'');
            IL::insert('log', [
                'user_id'=>$this->user_id,
                'operation_user'=> $this->user['name'],
                'operation_name'=>'删除',
                'operation_content'=>'删除规格成功',  
                'operation_type'=>3,
                'ip'=> Request()->ip(),
                'state'=>1,
                'createtime'=>date('Y-m-d H:i:s'),
             ]);
        }else{
            $date = array('code'=>20035,'msg'=>'删除规格失败','data'=>'');
            IL::insert('log', [
                'user_id'=>$this->user_id,
                'operation_user'=> $this->user['name'],
                'operation_name'=>'删除',
                'operation_content'=>'删除规格失败',  
                'operation_type'=>3,
                'ip'=> Request()->ip(),
                'state'=>0,
                'createtime'=>date('Y-m-d H:i:s'),
             ]);
        }
        return $date;
    }
    
    /**
     * 2018-4-17 日期格式
     * 曹振威 开发人
     * 单个添加/修改规格
     */
    public function standard_add_eidt($title = '',$systematics_id = 0,$id = 0){
        if(!$title){
            $date = array('code'=>20098,'msg'=>'规格名称（title）必须填写','data'=>'');
            exit(json_encode($date));
        }
        if(!$systematics_id){
            $date = array('code'=>20098,'msg'=>'规格所属的类目需要填写哦','data'=>'');
            exit(json_encode($date));
        }
        $stand_insert = [
            'system_id' => $this->system_id,
            'systematics_id' => $systematics_id,
            'title' => $title,
            'createtime' => date('Y-m-d H:i:s')
        ];
        if($id){
            // 编辑模式
            $where['system_id'] = $system_id;
            $where['id'] = $id;
            $row_type = 1;
            $row = Db::table('standard')->where($where)->update($stand_insert);
        }else{
            // 添加模式
            $row_type = 2;
            $row = Db::table('standard')->insert($stand_insert);
        }
        if($row){
            if($row_type == 1){
                $date = array('code'=>666,'msg'=>'编辑规格成功','data'=>'');
                IL::insert('log', [
                    'user_id'=>$this->user_id,
                    'operation_user'=> $this->user['name'],
                    'operation_name'=>'编辑',
                    'operation_content'=>'编辑规格成功', 
                    'operation_type'=>2,
                    'ip'=> Request()->ip(),
                    'state'=>1,
                    'createtime'=>date('Y-m-d H:i:s'),
                ]);
            }elseif($row_type == 2){
                $date = array('code'=>666,'msg'=>'操作成功','data'=>'');
                IL::insert('log', [
                    'user_id'=>$this->user_id,
                    'operation_user'=> $this->user['name'],
                    'operation_name'=>'编辑',
                    'operation_content'=>'编辑规格失败', 
                    'operation_type'=>2,
                    'ip'=> Request()->ip(),
                    'state'=>0,
                    'createtime'=>date('Y-m-d H:i:s'),
                ]);
            }
        }else{
            if($row_type == 1){
                $date = array('code'=>20034,'msg'=>'添加规格','data'=>'');
                IL::insert('log', [
                    'user_id'=>$this->user_id,
                    'operation_user'=> $this->user['name'],
                    'operation_name'=>'添加',
                    'operation_content'=>'添加规格失败', 
                    'operation_type'=>2,
                    'ip'=> Request()->ip(),
                    'state'=>1,
                    'createtime'=>date('Y-m-d H:i:s'),
                ]);
            }elseif($row_type == 2){
                $date = array('code'=>20034,'msg'=>'添加规格','data'=>'');
                IL::insert('log', [
                    'user_id'=>$this->user_id,
                    'operation_user'=> $this->user['name'],
                    'operation_name'=>'添加',
                    'operation_content'=>'添加规格成功', 
                    'operation_type'=>2,
                    'ip'=> Request()->ip(),
                    'state'=>0,
                    'createtime'=>date('Y-m-d H:i:s'),
                ]);
            }
        }
        return $date;
    }
    
    /**
     * 2018-05-31
     * czw
     * 根据产品品牌和系列生成产品名称
     */
    public function set_product_name($systematics_id = 0){
        $systematics_arr = $this->get_systematics($systematics_id);
        if(array_key_exists('xilie', $systematics_arr)){
            $product_name = $systematics_arr['brand']['title'].'/'.$systematics_arr['xilie']['title'];
        }elseif(array_key_exists('brand', $systematics_arr)){
            $product_name = $systematics_arr['brand']['title'];
        }else{
            $product_name = '';
        }
        $date = array('code'=>666,'msg'=>'产品名称生成成功','data'=>$product_name);
        return $date;
    }
    
    /**
     * 
     * 2018-4-12 日期格式
     * 2018-05-30 修改
     * 曹振威 开发人
     * 产品发布/更新
     * @param Request $Request
     * @return 
     */
    public function add_edit_product(Request $R) {
        $post = $R->post();
        $validate = Loader::validate('Product');
        $rule = $validate->check($post);
        if($rule !== true){
            $back['code'] = -1;
            $back['msg'] = $validate->getError();
            return $back;
        }


         $product_img = array();
         $files = $post['image'];
        if(array_key_exists('1',$files)){
            foreach ($files as $file){
                $product_img[] = $file;
            }
        }else{
            $product_img[] = $files[0];
        }
        $product_state = $this->warehouse_product($post['is_shelf']);

        $product_insert = [
            'pic_url' => $product_img[0],
//            'pic_url' => $product_img[0]['image'],
//            'thumb_url' => $product_img[0]['thumb'],
            'system_id' => $this->system_id,
            'business_id' => $this->business_id,
            'price' => $post['price'],
            'peer_price' => $post['peer_price'],
            'stock' => $post['stock'],
            'procurement_status' => $post['procurement_status'],
            'is_shelf' => $post['is_shelf'],
            'product_condition' => $post['product_condition'],
            'product_state' => intval($product_state),
            'product_code'      => $post['product_code'],
            'product_cate' => $post['product_cate'],
            'createtine' => date('Y-m-d H:i:s')
        ];
        if(isset($post['parts'])){
            $product_insert['parts'] = $post['parts'];
        }
        if(isset($post['systematics']['id'])){
            $arr_systematics = $this->get_systematics($post['systematics']['id']);
            if(!$arr_systematics){
                exit(json_encode(['code'=>20727,'msg'=>'类目必填','data'=>'']));
            }else{
                if(array_key_exists('systematics', $arr_systematics)){
                    $product_insert['category_id'] = $arr_systematics['systematics']['id'];
                }
                if(array_key_exists('child_systematics', $arr_systematics)){
                    $product_insert['type_id'] = $arr_systematics['child_systematics']['id'];
                }
                if(array_key_exists('brand', $arr_systematics)){
                    $product_insert['brand_id'] = $arr_systematics['brand']['id'];
                }
                if(array_key_exists('xilie', $arr_systematics)){
                    $product_insert['systematics_id'] = $arr_systematics['xilie']['id'];
                }
            } 
        }
        $product_name = $this->set_product_name($post['systematics']['id']);
        if(($post['product_cate']==0 && $post['product_condition']==7) || ($post['product_cate']==1 && $post['product_condition']!=7)){
            exit(json_encode(array('code'=>20001,'msg'=>'产品类型和产品成色冲突','data'=>'')));
        }
        if(!$product_name['data'] && !$post['product_name']){
            exit(json_encode(array('code'=>20201,'msg'=>'产品名称必填','data'=>'')));
        }else{
            $product_insert['product_name'] = $post['product_name'];
            $product_insert['full_name'] = $this->getProductConditionValue($post['product_condition']).' '.$product_name['data'].' '.$post['product_name'];
        }
        if($post['is_onsale'] == 1){
            $product_insert['is_onsale'] = 1;
        }else{
            $product_insert['is_onsale'] = 0;
        }
        if(!$post['store_id']){
            $product_insert['store_id'] = $this->store_id;
        }else{
            $product_insert['store_id'] = $post['store_id'];
        }
        if(!$post['staff_id']){
            $product_insert['staff_id'] = $this->user_id;
        }else{
            $product_insert['staff_id'] = $post['staff_id'];
        }
        if($post['product_source']){ 
            $source = Db::table('users')->where('phone',$post['product_source'])->find();
            if(empty($source)){
                $customer = $this->insert_user_customer($post['product_source'], $product_insert['staff_id']);
                $product_insert['origin_id'] = $customer;
                $product_insert['product_source'] = $post['product_source'];
            } else {
                $product_insert['origin_id'] = $source['id'];
                $product_insert['product_source'] = $post['product_source'];
            }
        }
        if($post['cost_price']){
            $product_insert['cost_price'] = $post['cost_price'];
        }
        if($post['product_cate'] == 1){
            $product_insert['product_condition'] = 7;
        }else{
            $product_insert['product_condition'] = $post['product_condition'];
        }
        if($post['additional']){
            $product_insert['additional'] = $post['additional'];
        }
        if($post['maintenance'] == ''){
            $product_insert['maintenance'] = 2;
        }else{
            $product_insert['maintenance'] = $post['maintenance'];
        }
        if($post['coordinate']){
            $product_insert['coordinate'] = $post['coordinate'];
        }
        if($post['library_age']){
            $product_insert['library_age'] = $post['library_age'];
        }else{
            $product_insert['library_age'] = 0;
        }
        if($post['synopsis']){
            $product_insert['synopsis'] = $post['synopsis'];
        }
        $standard_arr = $this->standard_attr($post['systematics']);
        if($standard_arr){
            $product_insert['standard_id'] = $standard_arr['standard'];
        }
        if($post['remark']){
            $product_insert['remark'] = $post['remark'];
        }
        if(!$post['product_sn']){
            $date = array('code'=>20089,'msg'=>'产品货号不能为空。','data'=>'');
            exit(json_encode($date));
        }elseif(isset($post['id'])){
           $row_product_sn = Db::table('product')->where(array('id'=>$post['id'],'product_sn'=>$post['product_sn']))->find();
           if(!$row_product_sn){
               $date = array('code'=>20094,'msg'=>'产品货号不能改变。','data'=>'');
               exit(json_encode($date));
           }
        }else{
            $row_product_sn = Db::table('product')->where('product_sn',$post['product_sn'])->find();
            if($row_product_sn){
               $date = array('code'=>20094,'msg'=>'产品货号已存在，请重新填写或生成。','data'=>'');
               exit(json_encode($date));
           }
        }
            if(array_key_exists('id', $post)){
                if(!empty($post['id'])){
                $product_id = $post['id'];
                $where['product_id'] = $product_id;
                $order = new Order();
                $order->check_order($product_id);
                Db::startTrans();
                try {
                    $data = Db::table('product')->where(array('id'=>$post['id'],'product_sn'=>$post['product_sn']))->update($product_insert);
                    $this->edit_product_image($product_id, $where, $product_img); // 编辑商品图片
                    $this->edit_attr($standard_arr, $product_id, $where); // 编辑产品属性
                    Db::commit();
                    $date = array('code'=>666,'msg'=>'编辑商品成功','data'=>'');
                    OL::insert([
                                'user_id'=> $this->user_id,
                                'module' => 'product', 
                                'module_id' => $product_id, 
                                'operation_type' => 2,  
                                'operation_content' => json_encode([
                                                    'product' => Db::table('product')->where(['id'=>$post['id']])->find()
                                                    ])
                            ]);
                } catch (Exception $exc) {
                    // 回滚事务
                    Db::rollback();
                    $date = array('code'=>20022,'msg'=>'编辑商品失败'.$exc,'data'=>'1');
                }
              }
            }else{
                Db::startTrans();
                try {
                    $product_insert['product_sn'] = $post['product_sn'];
                    $product_id = Db::table('product')->insertGetId($product_insert);
                    $this->add_product_image($product_id,$product_img);  // 添加商品图片
                    $this->add_attr($standard_arr, $product_id);  // 添加产品属性
                    // 提交事务
                    Db::commit(); 
                    $date = array('code'=>666,'msg'=>'添加商品成功','data'=>array('product_id',$product_id));
                    OL::insert([
                                'user_id'=> $this->user_id,
                                'module' => 'product', 
                                'module_id' => $product_id, 
                                'operation_type' => 1,  
                                'operation_content' => json_encode(['product' => Db::table('product')->where(['id'=>$product_id])->find()])
                            ]);
                } catch (Exception $exc) {
                // 回滚事务
                Db::rollback();
                $date = array('code'=>20022,'msg'=>'添加商品失败'.$exc,'data'=>'');
            }  
        }
        return $date;
    }

    public function getProductConditionValue($key)
    {
        $product_fineness = Db::table('product_fineness')->where(['id' => $key])->field('value')->find();
        return $product_fineness['value'];
    }
        
    /**
     * 2018-05-30
     * czw
     * 添加产品属性
     */

    public function add_attr($standard_arr = array(), $product_id = 0){
        if(!$product_id){
            $date = array('code'=>20104,'msg'=>'添加属性的产品id','data'=> '');
            exit(json_encode($date));
        }
        if(array_key_exists('attr',$standard_arr) && !empty($standard_arr['attr'])){
            foreach ($standard_arr['attr'] as $k_attr => $v_attr){
                $attr_insert[] = [
                    'product_id' => $product_id,
                    'standard_id' => $v_attr['standard_id'],
                    'title' => $v_attr['title'],
                    'createtime' => date('Y-m-d H:i:s')
                ];
            }
            $date = Db::table('attributevalue')->insertAll($attr_insert);
            IL::insert('log', [
                'user_id'=> $this->user_id,
                'operation_user'=> $this->user['name'],
                'operation_name'=>'添加', 
                'operation_content'=>'添加产品属性成功',
                'operation_type'=>2,
                'ip'=> Request()->ip(),
                'createtime'=>date('Y-m-d H:i:s'),
                'state'=>1
            ]);
        }else{
            $date = array();
        }
        return $date;
    }
        
    /**
     * 2018-05-30
     * czw
     * 编辑产品属性
     */

    public function edit_attr($standard_arr = array(), $product_id = 0,$where = array()){
        if(!$product_id){
            $date = array('code'=>20104,'msg'=>'添加属性的产品id','data'=> '');
            exit(json_encode($date));
        }
        if(array_key_exists('attr',$standard_arr) && !empty($standard_arr['attr'])){
            foreach ($standard_arr['attr'] as $k_attr => $v_attr){
                $attr_insert[] = [
                    'product_id' => $product_id,
                    'standard_id' => $v_attr['standard_id'],
                    'title' => $v_attr['title'],
                    'createtime' => date('Y-m-d H:i:s')
                ];
            }
            try{
                Db::table('attributevalue')->where($where)->setField('state',1);
                $date = Db::table('attributevalue')->insertAll($attr_insert);
                Db::commit();
                IL::insert('log', [
                    'user_id'=> $this->user_id,
                    'operation_user'=> $this->user['name'],
                    'operation_name'=>'编辑',
                    'product_id'=>$product_id,
                    'operation_content'=>'编辑产品属性成功',
                    'operation_type'=>2,
                    'ip'=> Request()->ip(),
                    'createtime'=>date('Y-m-d H:i:s'),
                    'state'=>1
                ]);
            }catch(Exception $exc){
                Db::rollback();
                IL::insert('log', [
                    'user_id'=> $this->user_id,
                    'operation_user'=> $this->user['name'],
                    'operation_name'=>'编辑',
                    'product_id'=>$product_id,
                    'operation_content'=>'编辑产品属性失败',
                    'operation_type'=>2,
                    'ip'=> Request()->ip(),
                    'createtime'=>date('Y-m-d H:i:s'),
                    'state'=>0
                ]);
            }
        }else{
            $date = array();
        }
        return $date;
    }
    
    /**
     * 2018-05-30
     * czw
     * 添加商品图片
     */
    
    public function add_product_image($product_id = 0 ,$image = array()){
        $img_insert = array();
        if(!$product_id || !$image[0]){
            $date = array('code'=>20102,'msg'=>'添加图片的产品id，和要添加的图片不能为空','data'=> '');
            exit(json_encode($date));
        }else{
            foreach ($image as $val){
                $img_insert[] = [
                    'product_id' => $product_id,
                    'pic_url' => $val,
//                    'pic_url' => $val['image'],
//                    'thumb_url' => $val['thumb'],
                    'createtime' => date('Y-m-d H:i:s')
                ];
            }
            $date = Db::table('productpic')->insertAll($img_insert);
        }
        return $date;
    }
    
    /**
     * 2018-05-30
     * czw
     * 编辑商品图片
     */
    
    public function edit_product_image($product_id = 0 ,$where = array() ,$image = array()){
        $img_insert = array();
        if(!$product_id || !$image[0] || !$where){
            $date = array('code'=>20103,'msg'=>'添加图片的产品id，和要更新的图片不能为空','data'=> '');
            exit(json_encode($date));
        }else{
            foreach ($image as $val){
                $img_insert[] = [
                    'product_id' => $product_id,
                    'pic_url' => $val,
                    'createtime' => date('Y-m-d H:i:s')
                ];
            }
            try{
                $row = Db::table('productpic')->where($where)->setField('state',1);
                $date = Db::table('productpic')->insertAll($img_insert);
                Db::commit();
            } catch (Exception $exc){
                Db::rollback();;
            }
        }
        return $date;
    }
    
    /**
     * 规格属性组合
     * @param type $systematics_arr
     * @return type
     */
    public function standard_attr($systematics_arr) {
        $standard_id = array();
        $date = array();
        $attr = array();
        $attr_arr = array();
        $standard = array();
        if(is_array($systematics_arr)){
            if(array_key_exists('standard', $systematics_arr) && !empty($systematics_arr['standard'])){
                foreach ($systematics_arr['standard'] as $k_s => $v_s) {
                    $standard_id[] = $v_s['stid'];
                    $standard = implode('-', $standard_id);
                    if(array_key_exists('attr', $v_s)){
                        foreach ($v_s['attr'] as $k_a => $v_a) {
                            $attr['title'] = $v_a;
                            $attr['standard_id'] = $v_s['stid'];
                            $attr_arr[] = $attr;
                        }
                    }
                }
            }else{
                $standard = $systematics_arr['standard'];
            }
        }else{
            $date = array('code'=>20066,'msg'=>'类目传参错误','data'=>'');
        }
        if($standard && $attr_arr){
            $date['standard'] = $standard;
            $date['attr'] = $attr_arr;
        }else{
            $date['standard'] = $standard;
        }
        return $date;
    }
    
    /**
     * 2018-4-10 日期格式
     * 曹振威 开发人
     * 产品删除/下架/上架
     */
    public function operat_product() {
        $user_id = $this->user_id;
        $system_id = $this->system_id;
        $ids = input('id');
        $type = input('type'); // 1:下架；2：删除；
        if(empty($ids) || empty($type)){
            $this->check_date = 1;
            $date = array('code'=>20021,'msg'=>'非法操作','data'=>'');
        }
        if($this->check_date != 0){
            exit(json_encode($date));
        }
        
        $product_ids = explode(",",$ids);
        $product = Db::table('product')->where(array('business_id'=> $this->business_id,'id'=>['IN',$product_ids],'state'=>0))->find();
        if(!$product){
            $date = array('code'=>20067,'msg'=>'不存在该产品','data'=>'');
            exit(json_encode($date));
        }
        $where = [
            'system_id' => $system_id,
            'business_id' => $this->business_id,
            'state'=>0,
        ];
        $product_up = [
            'is_shelf' => 1,
            'createtine' => date('Y-m-d H:i:s')
        ];
        if($type == 1){
            //下架
            Db::startTrans();//开启事务
            try{
                 $product_id = Db::table("product")->lock(TRUE)->where([
                     "id"=>["in",$product_ids]
                 ])->field("id")->select();
                Db::table("product")->where(["business_id"=>$this->business_id])->whereIn('id',$product_ids)->update($product_up);
                // 提交事务
                Db::commit();
                $date = array('code'=>666,'msg'=>'商品下架成功','data'=>'');
                foreach ($product_id as $key => $value) {
                    OL::insert([
                                'user_id'=> $this->user_id,
                                'module' => 'product', 
                                'module_id' => $value['id'], 
                                'operation_type' => 2,  
                                'operation_content' => json_encode(['product' => Db::table('product')->where(['id'=>$value['id']])->find()])
                            ]);
                }
                
            } catch (Exception $e) {
                // 回滚事务
                Db::rollback();
                
                $date = array('code'=>20025,'msg'=>'商品下架失败'.$e->getMessage() ,'data'=>'');
            }
            
        }elseif($type == 2){
            Db::startTrans();//开启事务
            try{
                 $product_id = Db::table("product")->lock(TRUE)->where([
                     "id"=>["in",$product_ids]
                 ])->field("id")->select();
                 $order = Db::table('orders_info')->whereIn('product_id',$product_ids)->where('state',0)->select();
                 if($order){
                     $date = array('code'=>22220,'msg'=>'该商品已存在订单，不可删除商品','data'=>'');
                     exit(json_encode($date));
                 }
                // 删除 
                Db::table("product")->where(["business_id"=>$this->business_id])->whereIn('id',$product_ids)->update(['state'=>1,'createtine' => date('Y-m-d H:i:s')]);
                // Db::table("review")->where(["business_id"=>$this->business_id])->whereIn('product_id',$product_ids)->update(['state'=>1,'createtime' => date('Y-m-d H:i:s')]);  //商品评论
                Db::table("productpic")->whereIn('product_id',$product_ids)->update(['state'=>1,'createtime' => date('Y-m-d H:i:s')]);  //商品图片
                Db::table("standard")->whereIn('product_id',$product_ids)->update(['state'=>1,'createtime' => date('Y-m-d H:i:s')]);  //商品规格
                // 提交事务
                Db::commit();
                $date = array('code'=>666,'msg'=>'商品删除成功','data'=>'');
                foreach ($product_id as $key => $value) {
                    OL::insert([
                                'user_id'=> $this->user_id,
                                'module' => 'product', 
                                'module_id' => $value['id'], 
                                'operation_type' => 4,  
                                'operation_content' => json_encode([
                                    'product' => Db::table('product')->where(['id'=>$value['id']])->find()
                                    ])
                            ]);
                }
                
            } catch (Exception $e) {
                // 回滚事务
                Db::rollback();
                $date = array('code'=>20048,'msg'=>'商品删除失败'.$e->getMessage(),'data'=>'');
            } 
        }
        return $date;
    }
    
    /**
     * 2018-4-11 日期格式
     * 曹振威 开发人
     * 产品列表
     */
    public function product_list($action = '') {
        //产品状态   仓库中  已售完  出售中
        $whereor = array();
        $subsql = '';
        $page_current = input('page',1);
        $reset = input('reset');
        $where = [
            'p.state' => 0,
            'p.business_id' => $this->business_id,
            'p.system_id' => $this->system_id,
//            'p.stock' => ['GT',0]
        ];
        $value_frist = input('value_frist');
        $brand = input('brand');
        if(!empty($brand))
        {
            $brand_ids = $this->getBrandIds($brand);
            $where['p.systematics_id'] = array('in',$brand_ids);
        }

        $long = input('long');
        if(isset($long) && $long != ''){
           if(input('long') == 1){
                $order = ['p.createtine'=>'desc'];
            }elseif(input('long') == 0){
               $order = ['p.createtine'=>'asc']; 
            } 
        }else {
            $order = ['p.id'=>'desc'];
        }
        input('procurement_status') ? $where['p.procurement_status'] = input('procurement_status') : FALSE;
        input('is_shelf') ? $where['p.is_shelf'] = input('is_shelf') : FALSE;
        input('store') ? $where['p.store_id'] = input('store') : FALSE;
        input('staff') ? $where['p.staff_id'] = input('staff') : FALSE;
        $begin_time = input('begin_time');
        $end_time = input('end_time');
        if($begin_time && empty($end_time)){
            $where['p.createtine'] = ['EGT time',$begin_time];
        }elseif (empty($begin_time) && $end_time) {
            $where['p.createtine'] = ['ELT',date('Y-m-d',strtotime("$end_time +1 day"))];
        } elseif($begin_time && $end_time) {
            $end_time = date('Y-m-d',strtotime("$end_time +1 day"));
            $where['p.createtine'] = ['between time',"$begin_time,$end_time"];
        }
        $price_name = input('price_name',0);
        $begin_price = input('begin_price');
        $end_price = input('end_price');
        if($price_name == 0){
            $price_name_select = 'price';
        }elseif ($price_name == 1) {
            $price_name_select = 'cost_price';
        }elseif($price_name == 2){
            $price_name_select = 'peer_price';
        }
        if($begin_price && empty($end_price)){
            $where['p.'.$price_name_select] = ['EGT',"$begin_price"];
        }elseif (empty ($begin_price) && $end_price){
            $where['p.'.$price_name_select] = ['ELT',"$end_price"];
        }elseif ($begin_price && $end_price) {
            $where['p.'.$price_name_select] = ['between',"$begin_price,$end_price"];
        }
        if($value_frist){
            $whereor['p.full_name|p.product_sn|p.product_source|p.coordinate'] = ['like',"%".input('value_frist')."%"];
            $subsql = Db::table('attributevalue')
                    ->where(array('title'=>['like',"%".input('value_frist')."%"]))
                    ->group('product_id')->column('product_id');
        }else{
            $subsql = Db::table('product')->alias('p')->where($where)->column('id');
        }
        if($reset == 1){
            $where = [
                'p.state' => 0,
                'p.business_id' => $this->business_id,
                'p.system_id' => $this->system_id,
    //            'p.stock' => ['GT',0]
            ];
            $whereor = array();
            $subsql = '';
        }
        $field = 'p.id,p.product_condition,pf.value product_condition_value,p.pic_url,p.stock,p.product_name,p.product_sn,'
                . 's.store_name,p.is_shelf, wc.value shelf_value,po.shares,po.views,p.procurement_status,ps.value procurement_value,p.cost_price,'
                . 'p.additional,st.name,p.product_source,p.createtine,p.peer_price,p.price,p.library_age,p.coordinate,'
                . 'b.business_name,p.is_onsale,p.systematics_id,p.product_state,pst.value product_state_value,p.brand_id,p.type_id,p.category_id';

        if(empty($action)){
           $product_list = Db::table('product')->alias('p')
                   ->join('store s','p.store_id=s.user_id','LEFT')
                   ->join('product_other po','p.id=po.product_id','LEFT')
                   ->join('staff st','st.user_id=p.staff_id','LEFT')
                   ->join('business b','p.business_id = b.business_id','LEFT')
                   ->join('product_fineness pf','p.product_condition = pf.id', 'LEFT')
                   ->join('warehouse_condition wc','p.is_shelf = wc.id', 'LEFT')
                   ->join('perchase_source ps','p.procurement_status = ps.id', 'LEFT')
                   ->join('product_state pst','pst.id = p.product_state','LEFT')
                   ->where($where)->where(function($obj)use($whereor,$subsql){
                       $obj->whereor($whereor)->whereor('p.id','in',$subsql);
                   })
                   ->order($order)
                   ->field($field)
                   ->paginate()->toArray();
            foreach ($product_list['data'] as $pkey => $pvalue) {
                if($pvalue['systematics_id']){
                    $systematics_arr = $this->set_product_name($pvalue['systematics_id']);
                }elseif($pvalue['brand_id']){
                    $systematics_arr = $this->set_product_name($pvalue['brand_id']);
                }else{
                    $systematics_arr = [];
                }

                if(!array_key_exists('data', $systematics_arr)){
                    $product_list['data'][$pkey]['pre_name'] = '';
                }else{
                    $product_list['data'][$pkey]['pre_name'] = $systematics_arr['data'];
                }
                $library_time = $this->get_library_time($pvalue['createtine']);
                $product_list['data'][$pkey]['library_time'] = $library_time;
            }
            $last_page = $product_list['last_page']; // 总页数
            if($page_current == 1 || $page_current<=$last_page){
                $date = array('code'=>666,'msg'=>'产品列表获取成功','data'=>$product_list);
                IL::insert('log', [
                    'user_id'=>$this->user_id,
                    'operation_user'=> $this->user['name'],
                    'operation_name'=>'查看', 
                    'operation_content'=>'查看产品列表',
                    'operation_type'=>1,
                    'ip'=> Request()->ip(),
                    'createtime'=>date('Y-m-d H:i:s'),
                    'state'=>1
                ]);
            }elseif($page_current>$last_page){
                $date = array('code'=>666,'msg'=>'没有这么多页哦','data'=>'');
            }
        }elseif($action == 'product_excel'){
            $date = Db::table('product')->alias('p')
                   ->join('store s','p.store_id=s.user_id','LEFT')
                   ->join('product_other po','p.id=po.product_id','LEFT')
                   ->join('staff st','st.user_id=p.staff_id','LEFT')
                   ->join('business b','p.business_id = b.business_id','LEFT')
                   ->where($where)->where(function($obj)use($whereor,$subsql){
                       $obj->whereor($whereor)->whereor('p.id','in',$subsql);
                   })
                   ->order($order)
                   ->field($field)
                   ->select();
        }
        return $date;
    }

    public function getBrandIds($brand_id)
    {
        if($brand_id<5){
            $brands = DB::table('systematics')
                    ->where(['id' => $brand_id])
                    ->whereor(['superior_id' => $brand_id])
                    ->whereor(['superior_gene'=>['like',$brand_id."-%"]])
                    ->field('id')
                    ->select();
        }elseif($brand_id>4 && $brand_id<42){
            $brands = DB::table('systematics')
                    ->where(['id' => $brand_id])
                    ->whereor(['superior_id' => $brand_id])
                    ->whereor(['superior_gene'=>['like',"%-".$brand_id]])
                    ->whereor(['superior_gene'=>['like',"%-".$brand_id."-%"]])
                    ->field('id')
                    ->select();
        }elseif($brand_id>41 && $brand_id<2686){
            $brands = DB::table('systematics')
                    ->where(['id' => $brand_id])
                    ->whereor(['superior_id' => $brand_id])
                    ->whereor(['superior_gene'=>['like',"%-".$brand_id]])
                    ->field('id')
                    ->select();
        }else{
            $brands = DB::table('systematics')
                    ->where(['id' => $brand_id])
                    ->field('id')
                    ->select();
        }
        
        $brand_ids = [];
        foreach ($brands as $brand) {
            $brand_ids []= $brand['id'];
        }
        return $brand_ids;
    }
    
    /**
     * 2018-4-12 日期格式
     * 曹振威 开发人
     * 产品信息详情
     */
    public function product_info($id = 0){
        if(!$id){
           $date = array('code'=>20202,'msg'=>'获取商品详情的产品编号不能为空','data'=>'');
            exit(json_encode($date)); 
        }
        $this->check_product($id);
        $where['p.id'] = $id;
        $where['p.state'] = 0;
        $where['p.system_id'] = $this->system_id;
        $where['p.business_id'] = $this->business_id;
        $where_img = [
            'state'=>0,
        ];
        $field = 'p.id,p.is_shelf,p.product_name,pf.value product_condition_value,p.product_cate,p.product_condition,p.business_id,'
                . 'p.procurement_status,p.price,wc.value shelf_value,p.peer_price,p.product_sn,p.createtine,ps.value procurement_value,'
                . 'p.product_code,p.cost_price,p.synopsis,p.category_id,p.type_id,p.brand_id,p.systematics_id,p.stock,'
                . 'p.maintenance,p.coordinate,p.library_age,p.remark,p.additional,'
                . 'p.product_source,p.staff_id sale_id,st.user_id staff_id,st.name staff_name,p.origin_id,p.receive_share,p.sale_share,'
                . 's.user_id store_id,s.store_name,p.pic_url,p.is_onsale,p.product_state,pst.value product_state_value,p.brand_id,p.type_id,'
                . 'p.category_id';
        $product_info = Db::table('product')->alias('p')
                ->join('staff st','p.staff_id = st.user_id','LEFT')
                ->join('store s','p.store_id = s.user_id','LEFT')
                ->join('product_fineness pf','p.product_condition = pf.id', 'LEFT')
                ->join('warehouse_condition wc','p.is_shelf = wc.id', 'LEFT')
                ->join('perchase_source ps','p.procurement_status = ps.id', 'LEFT')
                ->join('product_state pst','pst.id = p.product_state','LEFT')
                ->where($where)->field($field)->find();
        if(!$product_info['staff_id']){ // 采购员是商户或门店
            $row = Db::table('users')->where('id',$product_info['sale_id'])->field('id,name')->find();
            $product_info['staff_id'] = $row['id'];
            $product_info['staff_name'] = $row['name'];
        }
        if(!$product_info['store_id']){ // 商品所属商铺
            $row_business = Db::table('business')->where('business_id',$product_info['business_id'])->field('business_id,business_name')->find();
            $product_info['store_id'] = $row_business['business_id'];
            $product_info['store_name'] = $row_business['business_name'];
        }
        if($product_info['systematics_id']){
            $systematics_arr = $this->set_product_name($product_info['systematics_id']);
            $product_systematics = $this->get_systematics($product_info['systematics_id']);
        }elseif($product_info['brand_id']){
            $systematics_arr = $this->set_product_name($product_info['brand_id']);
            $product_systematics = $this->get_systematics($product_info['brand_id']);
        }elseif($product_info['type_id']){
            $systematics_arr = $this->set_product_name($product_info['type_id']);
            $product_systematics = $this->get_systematics($product_info['type_id']);
        }elseif($product_info['category_id']){
            $systematics_arr = $this->set_product_name($product_info['category_id']);
            $product_systematics = $this->get_systematics($product_info['category_id']);
        }else{
            $systematics_arr = [];
            $product_systematics = [];
        }
        if(!array_key_exists('data', $systematics_arr)){
            $product_info['pre_name'] = '';
        }else{
            $product_info['pre_name'] = $systematics_arr['data'];
        }
        $product_img = $this->get_img($id,$where_img);
        $product_standard = $this->get_standard($id);
        $product_info['systematics_info'] = $product_systematics;
        $product_info['systematics_info']['standard'] = $product_standard;
        $product_info['image'] = $product_img;
        if($product_info){
            if($product_info['systematics_id'] == null && $product_info['brand_id'] != null){
                $product_info['systematics_id'] = $product_info['brand_id'];
            }elseif($product_info['systematics_id'] == null && $product_info['brand_id'] == null && $product_info['type_id'] != null)
            {
                $product_info['systematics_id'] = $product_info['type_id'];
            }
            elseif($product_info['systematics_id'] == null && $product_info['brand_id'] == null && $product_info['type_id'] == null && $product_info['category_id'] != null)
            {
                $product_info['systematics_id'] = $product_info['category_id'];
            }
            $date = array('code'=>666,'msg'=>'产品信息获取成功','data'=>$product_info);
            IL::insert('log', [
                'user_id'=>$this->user_id,
                'operation_user'=> $this->user['name'],
                'product_id'=>$id,
                'operation_type'=>1,
                'operation_name'=>'查看', 
                'operation_content'=>'查看产品详情',
                'ip'=> Request()->ip(),
                'createtime'=>date('Y-m-d H:i:s'),
                'state'=>1
            ]);
        } else {
            $date = array('code'=>20028,'msg'=>'产品信息获取失败','data'=>''); 
            IL::insert('log', [
                'user_id'=>$this->user_id,
                'operation_user'=> $this->user['name'],
                'product_id'=>$id,
                'operation_type'=>1,
                'operation_name'=>'查看', 
                'operation_content'=>'查看产品详情',
                'ip'=> Request()->ip(),
                'createtime'=>date('Y-m-d H:i:s'),
                'state'=>0
            ]);
        }
        return $date;
    }
    
    public function get_img($product_id,$where=''){
        if($product_id){
            $where['product_id'] = $product_id;
            $where['state'] = 0;
            $date = Db::table('productpic')->where($where)->field('id,product_id,pic_url')->select();
        }else{
            $date = array('code'=>20071,'msg'=>'获取图片的产品id不能为空','data'=>'');
        }
        return $date;
    }
    
    public function get_standard($product_id,$where=array()) {
        $date = array();
        if($product_id){
            $where['id'] = $product_id;
            $where['state'] = 0;
            $standar_id = Db::table('product')->where($where)->value('standard_id');
            if($standar_id){
                $standar_arr = explode('-',$standar_id);
                foreach ($standar_arr as $key => $value) {
                    $row_standard = Db::table('standard')->where('id',$value)->field('id,title')->find();
                    $row_attr = $this->get_attr($product_id,$value);
                    $date[$key] = $row_standard; 
                    $date[$key]['attr'] = $row_attr; 
                }
            }
        }else{
            $date = array('code'=>20072,'msg'=>'获取规格的产品id不能为空','data'=>'');
            exit(json_encode($date));
        }
        return $date;
    }
    
    public function get_attr($product_id,$standard_id){
        $date = array();
        if($standard_id && $product_id){
            $where_attr = [
                'product_id' => $product_id,
                'standard_id' => $standard_id,
                'state' => 0,
            ];
            $date = Db::table('attributevalue')->where($where_attr)->field('id,product_id,standard_id,title')->select();
        }else{
            $date = array('code'=>20082,'msg'=>'获取属性的产品id不能为空','data'=>'');
            exit(json_encode($date));
        }
        return $date;
    }
    /**
     * 2018-05-31
     * czw 改
     * @param type $systematics
     * @return int
     */
//     public function get_systematics($systematics){
//         $date = array();
//         if($systematics){
//             $row = Db::table('systematics')->where('id',$systematics)->field('id,superior_id,superior_gene,title')->find();
//             $superior_id = $row['superior_id'];
//             $superior_gene = $row['superior_gene'];
//             $superior_gene_arr = explode('-',$superior_gene);
//             if($superior_gene){
//                 foreach ($superior_gene_arr as $sk => $sv) {
//                     $row_sy = Db::table('systematics')->where('id',$sv)->field('id,title')->find();
//                     if($sk == 0){
//                         $date['systematics'] = $row_sy;
//                         $date['child_systematics']['id'] = $row['id'];
//                         $date['child_systematics']['title'] = $row['title'];
//                     }elseif ($sk == 1) {
//                         $date['child_systematics'] = $row_sy;
//                         $date['brand']['id'] = $row['id'];
//                         $date['brand']['title'] = $row['title'];
//                     }elseif($sk == 2){
//                         $date['brand'] = $row_sy;
//                         $date['xilie']['id'] = $row['id'];
//                         $date['xilie']['title'] = $row['title'];
//                     }elseif($sk == 3){
//                         $date['xilie'] = $row_sy;
//                     }
//                 }
//             }else{
//                 $date['systematics'] = Db::table('systematics')->where('id',$systematics)->field('id,title')->find();
//             }
//         }else{
//             $date = [];
//         }
//         return $date;
//     }

    public function get_systematics($systematics)
    {
        $row = Db::table('systematics')->where('id',$systematics)->field('id,superior_id,superior_gene,title')->find();

        if($row != null)
        {
            if($row['superior_gene'] == 0){
                $date['systematics']['id'] = (int)$systematics;
                $date['systematics']['title'] = $row['title'];
            }else{
                $superior_gene_arr = explode('-',$row['superior_gene']);
                if(count($superior_gene_arr) == 1){
                    $date['systematics']['id'] = (int)$row['superior_id'];
                    $title = Db::table('systematics')->where('id',$row['superior_id'])->field('title')->find();
                    $date['systematics']['title'] = $title['title'];

                    $date['child_systematics']['id'] = (int)$systematics;
                    $date['child_systematics']['title'] = $row['title'];
                }elseif(count($superior_gene_arr) == 2){
                        $date['systematics']['id'] = (int)$superior_gene_arr[0];
                        $title = Db::table('systematics')->where('id',$superior_gene_arr[0])->field('title')->find();
                        $date['systematics']['title'] = $title['title'];

                        $date['child_systematics']['id'] = (int)$superior_gene_arr[1];
                        $title = Db::table('systematics')->where('id',$superior_gene_arr[1])->field('title')->find();
                        $date['child_systematics']['title'] = $title['title'];

                        $date['brand']['id'] = (int)$systematics;
                        $date['brand']['title'] = $row['title'];
                }elseif(count($superior_gene_arr) == 3){
                    $date['systematics']['id'] = (int)$superior_gene_arr[0];
                    $title = Db::table('systematics')->where('id',$superior_gene_arr[0])->field('title')->find();
                    $date['systematics']['title'] = $title['title'];
                    
                    $date['child_systematics']['id'] = (int)$superior_gene_arr[1];
                    $title = Db::table('systematics')->where('id',$superior_gene_arr[1])->field('title')->find();
                    $date['child_systematics']['title'] = $title['title'];
                    
                    $date['brand']['id'] = (int)$superior_gene_arr[2];
                    $title = Db::table('systematics')->where('id',$superior_gene_arr[2])->field('title')->find();
                    $date['brand']['title'] = $title['title'];
                    
                    $date['xilie']['id'] = (int)$systematics;
                    $date['xilie']['title'] = $row['title'];
                }
            }

        }else{
            $date = [];
        }

        return $date;
    }
    
    public function match_shelf($id) {
        $D = new Dropdown();
        $warehouse_condition = $D->warehouse_condition();
        return $warehouse_condition['data'][$id-1];
    }
    
    /**
     * 2018-04-27 开发日期
     * 曹振威 开发人
     * 查看产品轨迹
     * @return string
     */
    public function select_product_route() {
        $id = input('id');
        if(!$id){
           $date = array('code'=>20021,'msg'=>'查看商品轨迹的商品编号不能为空','data'=>'');
            exit(json_encode($date)); 
        }
        $this->check_product($id);
        $where['p.system_id'] = $this->system_id;
        $where['p.business_id'] = $this->business_id;
        $where['p.id'] = $id;
        $where['p.state'] = 0;
        $field = 'p.id,p.is_shelf, wc.value shelf_value, p.product_sn,p.cost_price,'
                . 'p.peer_price,p.price,s.store_name,p.procurement_status, ps.value procurement_value';
        $route = Db::table('product')
                ->alias('p')
                ->join('store s','p.store_id=s.user_id','LEFT')
                ->join('warehouse_condition wc','p.is_shelf=wc.id','LEFT')
                ->join('perchase_source ps','p.procurement_status=ps.id','LEFT')
                ->where($where)->field($field)
                ->find();
        $log_field = 'u.name,op.operation_content,op.operation_time';
        $log = Db::table('operation_log')->alias('op')
                ->join('users u','u.id=op.user_id','LEFT')
                ->where(array('op.module'=>'product','module_id'=>$id,))
                ->field($log_field)
                ->order('op.id desc')
                ->select();
        if(!$log){
            $ol_log = [];
        }else{
           foreach ($log as $lkey=>$lvalue){
               $new = json_decode($lvalue['operation_content'],true);
               $ol_log[] = $new['product'];
           } 
        }
        $operation_content = [];
        $a = [];
        if($ol_log){
           $i = 0;
            foreach ($ol_log as $olk=>$olv){
                if($olv){
                    $arr_new = $this->check_log($olv);
                    if(!empty($arr_new)){
                        $arr = $this->match_shelf($arr_new['is_shelf']);
                       $operation_content[$i]['operation_content'] = $arr;
                       $operation_content[$i]['operation_user'] = $log[$olk]['name'];
                       $operation_content[$i]['createtime'] = $log[$olk]['operation_time'];
                       $i++;
                    }
                }
            } 
        }
        $route['route'] = $operation_content; 
        $date = array('code'=>666,'msg'=>'产品轨迹获取成功','data'=>$route);
        return $date;
    }
    
    public function check_log($array = array()){
        $arr_new = [];
        $arr = array('is_shelf'=>'');
        foreach ($array as $ak=>$av) {
            if(array_key_exists("$ak", $arr)){
                $arr_new = [$ak=>$av];
            }
        }
        return $arr_new;
    }
    /**
     * 2018-04-28
     * 曹振威
     * 产品上架
     * @return string
     */
    public function product_onsale() {
        $where = array();
        $id = input('id');
        if($this->business_id){
            $where['business_id'] = $this->business_id;
        }
        if($id){
            $product_ids = explode(",",$id);
            $product = Db::table('product')->where(array('business_id'=>$this->business_id,'id'=>['IN',$product_ids],'state'=>0))->find();
            if(!$product){
                $date = array('code'=>20067,'msg'=>'不存在该产品','data'=>'');
                exit(json_encode($date));
            }
            $row = Db::table('product')->where($where)->whereIn('id',$product_ids)->setField('is_shelf',2);
            if($row){
                $date = array('code'=>666,'msg'=>'产品上架成功','data'=>'');
                foreach ($product_ids as $key => $value) {
                    OL::insert([
                                'user_id'=> $this->user_id,
                                'module' => 'product', 
                                'module_id' => $value, 
                                'operation_type' => 4,  
                                'operation_content' => json_encode([
                                    'product' => Db::table('product')->where(['id'=>$value])->find()
                                    ])
                            ]);
                }
            }else{
                $date = array('code'=>20062,'msg'=>'产品上架失败','data'=>'');
            }
        }else{
            $date = array('code'=>20021,'msg'=>'非法操作','data'=>'');
        }
        return $date;
    }
    
    /**
     * 2018-04-20
     * 曹振威
     * 产品列表导出
     */
    public function product_excel() {
        $data = $this->product_list('product_excel');
        $key = [
            '产品编号','产品名称','产品图片','产品现价','成本价','同行价','产品数量'
        ];
        $keyname = array('id','product_name','pic_url','price','cost_price','peer_price','stock');
        $styleArray = [
            'font' => ['bold' => true]
        ];
        common::output_excel($key, $data, $keyname, '产品列表',$styleArray);
    }
    
    /**
     * 返回库存状态
     * @param type $product_id
     */
    public function get_stock_status($product_id = '',$num=0) {
        $i = 0;
        if(!$product_id){
            $i = 1;
            $date = array('code'=>20084,'msg'=>'获取库存的产品id不能为空','data'=>'');
        }else{
            $stock = Db::table('product')->where('id',$product_id)->value('stock');
            if(!$stock || $stock <= 0){
                $row = Db::table('product')->where('id',$product_id)->setField('is_onsale',1);
                $i = 1;
                $date = array('code'=>20085,'msg'=>'库存为空','data'=>'');
            }elseif($stock<$num){
                $i = 1;
                $date = array('code'=>20086,'msg'=>'库存太少了，买的太多了','data'=>'');
            }
        }
        if($i == 1){
            exit(json_encode($date));
        }
    }
    
    /**
     * 2018-06-01
     * czw
     * 验证产品是否存在
     * @param type $product_id
     */
    public function check_product($product_id = 0){
        $product_info = Db::table('product')->where(array('business_id'=>$this->business_id,'id'=>$product_id,'state'=>0))->find();
        if(!$product_info){
            $date = array('code'=>20067,'msg'=>'不存在该产品','data'=>'');
            exit(json_encode($date));
        }
        return $product_info;
    }
    
    /**
     * 2018-07-01  改
     * 2018-06-05
     * czw
     * 验证商品商品状态是否可以售出
     */
    public function check_shelf($product_id = 0) {
        if(!$product_id){
            $date = array('code'=>29993,'msg'=>'检验库存状态的产品编号不能为空','data'=>'');
        }else{
            $product_info = $this->check_product($product_id);
            $order = Db::table('orders_info')->where(array('product_id'=>$product_id,'is_nursing'=>0,'status'=>['NEQ',7],'state'=>0))->select();
            if(!in_array($product_info['product_state'], array('1','2','3','4','15'))){
                $date = array('code'=>29997,'msg'=>'该商品的库存状态似乎不能售出','data'=>'');
            }elseif($product_info['is_own'] == 1){
                $date = array('code'=>29997,'msg'=>'非自有商品，不能售出','data'=>'');
            }elseif($order){
                $date = array('code'=>29997,'msg'=>'该商品的已存在售出订单','data'=>'');
            }else{
                $date = array('code'=>666,'msg'=>'该商品的库存状态可以售出','data'=>'');
            }
        }
        return $date;
    }
    
    public function insert_user_customer($product_source,$staff_id) {
        $user_insert = [
            'system_id' => $this->system_id,
            'business_id' => $this->business_id,
//            'store_id' => $this->store_id,
            'phone' => $product_source,
            'createtime' => date('Y-m-d H:i:s'),
            'is_customer'=>1
        ];
        $customer = Db::table('users')->insertGetId($user_insert);
        $customer_insert = [
            'system_id' => $this->system_id,
            'business_id' => $this->business_id,
            'store_id' => $this->store_id,
            'sales_id' => $staff_id,
            'user_id' => $customer,
            'createtime' => date('Y-m-d H:i:s'),
        ];
        Db::table('customer')->insert($customer_insert);
        return $customer;
    }
    
    public function get_library_time($createtine) {
        $second1 = strtotime(date('Y-m-d H:i:s'));
        $second2 = strtotime($createtine);
        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
          }
          return intval(($second1 - $second2) / 86400);
    }
    
    /**
     * 2018-07-01
     * czw
     * 库存状态对应商品情况
     */
    public function warehouse_product($warehouse_condition) {
        switch ($warehouse_condition) {
            case '1':
                return 2;
                break;

            case '2':
                return 1;
                break;

            case '3':
                return 4;
                break;
            
            default:
                return 0;
                break;
        }
    }


    /**
     * @Notes:添加商品需要加载的下拉列表
     * @param Request $request
     * @return array
     * @author: LiBaoJin
     * @Time:
     */
    public  function set_add_merchant(Request$request){
        $postData = $request->post();
        $rules = [
            'token'=>'require'
        ];
        $rule = $this->validate($postData,$rules);
        if($rule !== true){
            return DataReturnService::returnError(-1,$rule);
        }

        $user = Base::getUserByTokenWithPhone($postData['token']);
        if(!isset($user['data'])){
            return DataReturnService::returnError(-1,'token过期');
        }

        $data = [
            'product_fineness'=>'',//商品成色
            'perchase_source'=>'',//采购类别
            'warehouse_condition'=>'',//库存状态
            'store_list'=>'',          //所在门店以及本门店采购员
        ];

        $fineness_data = ProductService::table_select('product_fineness',['state'=>0]);
        if(isset($fineness_data['code'])&&$fineness_data['code']=='666'){
            $data['product_fineness'] = $fineness_data['data'];
        }
        $source_data = ProductService::table_select('perchase_source',['state'=>0]);
        if(isset($source_data['code'])&&$source_data['code']=='666'){
            $data['perchase_source'] = $source_data['data'];
        }
        $condition_data = ProductService::table_select('warehouse_condition',['state'=>0]);
        if(isset($condition_data['code'])&&$condition_data['code']=='666'){
            $data['warehouse_condition'] = $condition_data['data'];
        }
        $store_data = ProductService::store_list($user['data']['id']);
        if(isset($store_data['code'])&&$store_data['code']=='666'){
            $data['store_list'] = $store_data['data'];
        }
        return DataReturnService::returnOk($data,'ok');
    }
    /**
     * @Notes:获取商品类型以及子分类
     * @param Request $request
     * @return array
     * @author: LiBaoJin
     * @Time:
     */
    public function systematics_list(Request$request){
        $postData = $request->post();
        $rules = [
            'token'=>'require'
        ];
        $rule = $this->validate($postData,$rules);
        if($rule !== true){
            return DataReturnService::returnError(-1,$rule);
        }
        try{
            $user = Base::getUserByTokenWithPhone($postData['token']);
            $postData['superior_id'] = isset($postData['superior_id'])?$postData['superior_id']:0;
            if(empty($postData['type'])){
                $where = [
                    'system_id'=>isset($user['data']['system_id'])?$user['data']['system_id']:1,
                    'state' => 0,
                    'superior_id'=>$postData['superior_id'],
                ];
            }else{
                $where = [
                    'system_id'=>isset($user['data']['system_id'])?$user['data']['system_id']:1,
                    'state' => 0,
                    'superior_id'=>$postData['superior_id'],
                    'type' => $postData['type'],
                ];
            }
            $systematics_data = Db::table('systematics')
                ->where($where)
                ->field('id,superior_id,type,title,label')
                ->select();
            IL::insert('log', [
                'user_id'=>isset($user['data']['id'])?$user['data']['id']:1,
                'operation_user'=> $user['data']['name'],
                'operation_name'=>'查看',
                'operation_content'=>'查看类目/品牌/系列',
                'operation_type'=>1,
                'ip'=> Request()->ip(),
                'state'=>1,
                'createtime'=>date('Y-m-d H:i:s'),
            ]);
            return DataReturnService::returnOk($systematics_data,'ok');
        }catch(Exception$e){
            return DataReturnService::returnError(-1,$e->getMessage());
        }
    }

}